var FormEX = require(path.join(__dirname, 'form.js'));
var interface = require(path.join(__dirname, '_list.js')).interface;
var dialogEX = Require('./component/_dialog.js');
var dialog = require('electron').remote.dialog;
var inputEX = FormEX.input;
var textareaEX = FormEX.textarea;
var compressFile = Require('./component/getBase64.js');
var saveFile = Require('./component/saveFile.js');
var formatDate = Require('./component/formatDate.js');
// 编辑模式接口列表
var EditorInterfaceList = function (data, parent) {
    this.data = data;
    this.parent = parent;
    this.event = this.parent.event;
    this.html = $('<div class="answerBox list custom-scroll theme-scroll list"></div>');
    this.empty = $('<div class="empty">没有内容</div>');
    this.box = $('<div></div>');
    this.item = {};
    this.box.append(this.empty);
    this.html.append(this.box);
    this.set(data);

};
EditorInterfaceList.prototype.render = function () {
    return this.html;
};
EditorInterfaceList.prototype.append = function (data) {
    if (this.item.hasOwnProperty(data.id)) {
        this.active(data.id, () => {
            this.item[data.id].html.addClass('interface_flicker');
            setTimeout(() => {
                this.item[data.id].html.removeClass('interface_flicker');
            }, 500);
        });
    } else {
        this.item[data.id] = new interface(data, this);
        var deleteButton = $('<i class="fa fa-trash-o"></i>').click((e) => {
            event.stopPropagation();
            this.remove(data.id);
        });
        this.box.append(this.item[data.id].render());
        this.item[data.id].title.append(deleteButton);
        this.active(data.id, () => { });
        if (this.empty) {
            this.empty.remove();
            this.empty = null;
        };
    };
};
EditorInterfaceList.prototype.remove = function (id) {
    if (this.item.hasOwnProperty(id)) {
        dialogEX({
            title: '警告',
            body: '<div style="padding:20px;">是否删除关联?</div>',
            buttons: [{
                text: '是',
                event: (dialogEvent) => {
                    this.item[id].html.remove();
                    delete this.item[id];
                    dialogEvent.close();
                },
            }, {
                text: '否',
                event: (dialogEvent) => {
                    dialogEvent.close();
                },
            }],
            width: 400,
            height: 200
        });
    };
};
EditorInterfaceList.prototype.active = function (id, cb) {
    var moveObj = () => {
        var obj = this.item[id].html;
        var Min = this.html.offset().top;
        var Max = Min + 300;
        var top = obj.offset().top;
        var height = 23;
        if (top < Min) {
            this.html.scrollTop(this.html.scrollTop() - 10);
            setTimeout(() => {
                moveObj();
            }, 5)
        } else if (top > Max - height) {
            this.html.scrollTop(this.html.scrollTop() + 10);
            setTimeout(() => {
                moveObj();
            }, 5)
        };
    };
    moveObj();
};
EditorInterfaceList.prototype.get = function () {
    var data = [];
    for (const key in this.item) {
        if (this.item.hasOwnProperty(key)) {
            const element = this.item[key];
            data.push(element.config.id);
        }
    };
    return data;
};
EditorInterfaceList.prototype.set = function (data) {
    this.box.empty();
    this.event.getInterface(data, (docs) => {
        for (let i = 0; i < docs.length; i++) {
            const element = docs[i];
            this.append(element);
        };
    });
};
// 编辑模式
var editorBox = function (data, parent) {
    this.html = $('<div class="editorBox"></div>');
    this.parent = parent;
    this.event = this.parent.event;
    this.input = inputEX({
        size: 'block',
        jude: {
            name: '标题',
            rules: ['notNull']
        },
        readonly: false,
        placeholder: '标题',
    });
    this.textarea = textareaEX({
        size: 'block',
        jude: {
            name: '备注',
            rules: []
        },
        readonly: false,
        placeholder: '备注',
    });
    this.input.set(data.title);
    this.textarea.set(data.description);
    this.confirm = $('<div class="confirm button">确定</div>');
    this.cancel = $('<div class="cancel button">取消</div>');
    this.cf = $('<div class="cf"></div>');
    this.cancel.click(() => {
        parent.hide();
    });
    this.confirm.click(() => {
        this.get((data) => {
            parent.save(data);
        });
    });
    this.searchBox = $('<div class="searchBox"></div>');
    this.search = Require('./component/_search.js')();
    this.searchBox.append(this.search.render());
    this.search.on('renderList', (event, data, contentType) => {
        event.loading();
        this.event.searchInterface(data, contentType, (docs) => {
            event.setData(docs);
            if (docs.length == 0) {
                event.showMark();
            };
            event.loading();
        });
    });
    this.parent = parent;
    this.answerBox = new EditorInterfaceList(data.interface, this.parent);
    this.imageList = new EditorImageList(data.images, this.parent);
    this.pushToAnswerBox = $('<div class="pushToAnswerBox"><i class="fa fa-angle-right"></i></div>');
    this.pushToAnswerBox.find('i').click(() => {
        if (this.search.activeObj) {
            this.answerBox.append(this.search.activeObj.config);
        };
    });
    this.files = [];
    this.html.append(this.input.render()).append(this.textarea.render())
    this.html.append(this.searchBox);
    this.html.append(this.pushToAnswerBox);
    this.html.append(this.answerBox.render()).append('<div class="cf"></div>');
    this.html.append(this.imageList.render()).append('<div class="cf"></div>');
    this.html.append(this.confirm).append(this.cancel).append('<div class="cf"></div>');
};
editorBox.prototype.render = function () {
    return this.html;
};
editorBox.prototype.get = function (callBack) {
    this.input.get((error, inputDoc) => {
        if (error) {
            dialogEX({
                title: '警告',
                body: '<div style="padding:20px;">' + error + '</div>',
                buttons: [{
                    text: '确定',
                    event: (event) => {
                        event.close();
                    },
                }],
                width: 400,
                height: 200,
            });
        } else {
            this.textarea.get((error, textareaDoc) => {
                if (error) {
                    dialogEX({
                        title: '警告',
                        body: '<div style="padding:20px;">' + error + '</div>',
                        buttons: [{
                            text: '确定',
                            event: (event) => {
                                event.close();
                            },
                        }],
                        width: 400,
                        height: 200,
                    });
                } else {
                    callBack({
                        title: inputDoc,
                        description: textareaDoc,
                        answerBox: this.answerBox.get(),
                        imageList: this.imageList.get()
                    });
                }
            });
        }
    });
};
// 编辑模式图片列表
var EditorImageList = function (data, parent) {
    this.data = data;
    this.parent = parent;
    this.event = this.parent.event;
    this.html = $('<div class="imageList"></div>');
    this.title = $('<div class="imageList_title">图片列表</div>');
    this.addButton = $('<div class="addButton"><i class="fa fa-plus-circle"></i>添加图片</div>');
    this.html.append(this.title.append(this.addButton));
    this.addButton.click(() => {
        this.readFile();
    });
    this.showList = [];
    this.creatList = [];
    this.deleteList = [];
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.addItem(element, i);
        this.showList.push(element);
    };
    this.imagePreview = new imagePreview(this, this.showList, this.event);
};
EditorImageList.prototype.render = function () {
    return this.html;
};
EditorImageList.prototype.readFile = function () {
    var input = inputEX({
        size: 'normal',
        jude: {
            name: '标题',
            rules: ['notNull']
        },
        readonly: false,
        placeholder: '标题',
    });
    var html = $('<div class="note_readFile"></div>');
    var button = $('<div class="btn" style="margin:0">选择文件</div>');
    var base64 = null;
    button.click(() => {
        dialog.showOpenDialog({
            title: '选择图片',
            filters: [
                { name: '图片', extensions: ['jpg', 'png'] },
            ],
            properties: ['openFile', 'createDirectory'],
        }, function (filenames) {
            if (filenames) {
                var file = filenames[0];
                var pos = file.lastIndexOf("\\");
                var name = file.substring(pos + 1);
                compressFile(file, function (error, data) {
                    if (error) {
                        dialogEX({
                            title: '警告',
                            body: '<div style="padding:20px;">' + error + '</div>',
                            buttons: [{
                                text: '确定',
                                event: (event) => {
                                    event.close();
                                },
                            }],
                            width: 400,
                            height: 200,
                        });
                    } else {
                        base64 = data;
                        input.set(name);
                    };
                });
            };
        });
    });
    html.append(input.render()).append('<div style="clear:both"></div>').append(button);
    dialogEX({
        title: '上传图片',
        body: html,
        buttons: [{
            text: '确定',
            event: (dialogEvent) => {
                input.get((error, doc) => {
                    if (error) {
                        dialogEX({
                            title: '警告',
                            body: '<div style="padding:20px;">' + error + '</div>',
                            buttons: [{
                                text: '确定',
                                event: (event) => {
                                    event.close();
                                },
                            }],
                            width: 400,
                            height: 200,
                        });
                    } else {
                        this.addItem({
                            data: base64,
                            title: doc
                        });
                    }
                    dialogEvent.close();
                });
            },
        }],
        width: 400,
        height: 205
    });
};
EditorImageList.prototype.addItem = function (data, index) {
    if (!data.id) {
        var index = this.showList.length;
        this.showList.push(data);
        var item = new imgItem(data, this, false, index);
        this.creatList.push(item);
    } else {
        var item = new imgItem(data, this, false, index);
    };
    this.html.append(item.render());
};
EditorImageList.prototype.removeCreatItem = function (data) {
    for (let i = 0; i < this.creatList.length; i++) {
        const element = this.creatList[i];
        if (element === data) {
            this.creatList.splice(i, 1);
            break;
        };
    }
};
EditorImageList.prototype.removeShowItem = function (data) {
    this.deleteList.push(data.data.id);
};
EditorImageList.prototype.get = function () {
    var creatData = [];
    for (let i = 0; i < this.creatList.length; i++) {
        const element = this.creatList[i];
        creatData.push(element.data);
    };
    var data = {
        deleteImg: this.deleteList,
        creatImg: creatData,
    };
    return data;
};
// 图片子对象
var imgItem = function (data, parent, unDelete, index) {
    this.index = index;
    this.parent = parent;
    this.data = data;
    this.event = this.parent.event;
    this.html = $('<div class="img_item"></div>');
    var text = $('<div class="img_item_text">' + data.title + '</div>');
    if (!unDelete) {
        var _delete = $('<div class="fa delete fa-trash-o" title="删除"></div>');
        _delete.click(() => {
            this.delete();
        });
    };
    this.html.append(text).append(_delete);
    text.click(() => {
        this.lookimg();
    });
};
imgItem.prototype.render = function () {
    return this.html;
};
imgItem.prototype.lookimg = function () {
    if (this.parent.hasOwnProperty('showList')) {
        this.parent.imagePreview.show(this.index, this.parent.showList);
    } else {
        this.parent.imagePreview.show(this.index, this.parent.data);
    };
};
imgItem.prototype.delete = function () {
    dialogEX({
        title: '警告',
        body: '<div style="padding:20px;">是否删除图片?</div>',
        buttons: [{
            text: '是',
            event: (dialogEvent) => {
                this.html.remove();
                if (this.data.id) {
                    this.parent.removeShowItem(this);
                } else {
                    this.parent.removeCreatItem(this);
                };
                dialogEvent.close();
            },
        }, {
            text: '否',
            event: (dialogEvent) => {
                dialogEvent.close();
            },
        }],
        width: 400,
        height: 200
    });
};
//图片预览框架
var imagePreview = function (parent, data, event) {
    this.getImage = event.getImages;
    this.data = data;
    this.parent = parent;
    this.index = null;
    this.imageData = {
        width: 0,
        height: 0,
        zoom: 1,
        moveX: 0,
        moveY: 0,
        top: 0,
        left: 0,
        title: '',
        data: '',
    };
    this.imageElement = null;
    this.timer = null;
};
imagePreview.prototype.template = function () {
    var html = '';
    html += '<div class="dialog TA" style="z-index:9999">';
    html += '	<div class="dialog-bg"></div>';
    html += '	<div class="dialog-main TA" style="z-index:10000;width:90%;height:90%;position:absolute;left:5%;top:5%;margin:0">';
    html += '		<div class="dialog-title cl">';
    html += '			<div class="dialog-title-text"></div>';
    html += '			<div class="dialog-close"><i class="fa fa-close"></i></div>';
    html += '		</div>';
    html += '		<div class="dialog-body imagePreviewTool" style="">';
    html += '           <div class="imageBox TA_f"></div>';
    html += '		    <div class="pre TA"><div class="fa fa-angle-left"></div></div>';
    html += '		    <div class="next TA"><div class="fa fa-angle-right"></div></div>';
    html += '		    <div class="message TA_f">已经是最后一张了</div>';
    html += '		    <div class="toolBox">'
    html += '		        <div class="small fa fa-image" title="原始尺寸"></div>';
    html += '		        <div class="big fa fa-tv" title="适应屏幕"></div>';
    html += '		        <div class="save fa fa-download" title="保存到本地"></div>';
    html += '		    </div>';
    html += '		</div>';
    html += '	</div>';
    html += '</div>';
    this.html = $(html);
    // 上一页
    this.pre = this.html.find('.pre .fa');
    this.pre.click(() => {
        if (this.index == 0) {
            this.showMessage('已经是第一张了');
        } else {
            this.index -= 1;
            this.clearImage();
            this.setImage(this.index);
        };
    });
    // 下一页
    this.next = this.html.find('.next .fa');
    this.next.click(() => {
        if ((this.index + 1) == this.data.length) {
            this.showMessage('已经是最后一张了');
        } else {
            this.index += 1;
            this.clearImage();
            this.setImage(this.index);
        }
    });
    // 保存
    this.save = this.html.find('.save');
    this.save.click(() => {
        dialog.showSaveDialog({
            title: '保存图片',
            defaultPath: this.imageData.title,
            filters: [
                { name: 'jpg', extensions: ['jpg'] },
                { name: 'png', extensions: ['png'] }
            ],
        }, (filenames) => {
            if (filenames) {
                saveFile(filenames, this.imageData.data, () => {
                    this.showMessage('保存成功');
                });
            };
        })
    });
    // 标题
    this.title = this.html.find('.dialog-title-text');
    // 图片控制盒子
    this.imageBox = this.html.find('.imageBox');
    // 工具栏
    this.Tool = this.html.find('.imagePreviewTool');
    // 关闭
    this.html.find('.dialog-close').click(() => {
        this.closeEvent();
    });
    // 原尺寸
    this.small = this.html.find('.small');
    this.small.click(() => {
        this.BigControl(false);
    });
    // 适应屏幕
    this.big = this.html.find('.big');
    this.big.click(() => {
        this.BigControl(true);
    });
    this.message = this.html.find('.message');
};
imagePreview.prototype.show = function (index, data) {
    this.data = data;
    this.template();
    $('body').css({
        'user-select': 'none'
    });
    $('body').append(this.html);
    document.onkeydown = event => {
        if (event.keyCode == 27) {
            this.closeEvent();
        }
    };
    this.index = index;
    this.setImage(index);
};
imagePreview.prototype.BigControl = function (isBig) {
    var zoom = 1;
    this.imageData.moveX = 0;
    this.imageData.moveY = 0;
    var tw = this.Tool.width();
    var th = this.Tool.height();
    if (isBig) {
        if (this.imageData.width > this.imageData.height) {
            zoom = tw / this.imageData.width - 0.02;
        } else {
            zoom = th / this.imageData.height - 0.02;
        };
    };
    this.Control(zoom);
};
imagePreview.prototype.Control = function (zoom) {
    var tw = this.Tool.width();
    var th = this.Tool.height();
    this.imageData.zoom = zoom;
    this.imageData.top = (th - this.imageData.height * zoom) / 2;
    this.imageData.left = (tw - this.imageData.width * zoom) / 2;
    this.imageBox.css({
        width: this.imageData.width * zoom,
        height: this.imageData.height * zoom,
        top: this.imageData.top,
        left: this.imageData.left
    });
};
imagePreview.prototype.move = function () {
    this.Tool.mousedown((e) => {
        this.imageBox.removeClass('TA_f');
        var left = e.clientX;
        var top = e.clientY;
        this.Tool.on('mousemove', (e) => {
            this.moveEvent(left, top, e);
        });
    });
    this.Tool.mouseup((e) => {
        this.imageBox.addClass('TA_f');
        this.Tool.off('mousemove');
        this.imageData.left = parseInt(this.imageBox.css('left'));
        this.imageData.top = parseInt(this.imageBox.css('top'));
    });

    this.Tool.mouseout((e) => {
        this.imageBox.addClass('TA_f');
        this.Tool.off('mousemove');
        this.imageData.left = parseInt(this.imageBox.css('left'));
        this.imageData.top = parseInt(this.imageBox.css('top'));
    });

};
imagePreview.prototype.zoomEvent = function () {
    this.Tool.on('mousewheel', (event) => {
        if (event.deltaY > 0) {
            var __zoom = this.imageData.zoom * 0.1;
            var zoom = this.imageData.zoom += __zoom;
            if (zoom > 10) {
                zoom = 10;
                this.showMessage('已经缩放到最大程度');
            };
            this.Control(zoom);
        } else {
            var __zoom = this.imageData.zoom * 0.1;
            var zoom = this.imageData.zoom -= __zoom;
            if (zoom < 0.1) {
                zoom = 0.01;
                this.showMessage('已经缩放到最小程度');
            };
            this.Control(zoom);
        };
        console.log(event.deltaY);
    });
};
imagePreview.prototype.moveEvent = function (x, y, e) {
    var moveX = e.clientX - x;
    var moveY = e.clientY - y;
    this.imageData.moveX = moveX;
    this.imageData.moveY = moveY;
    this.imageBox.css({
        top: this.imageData.top + this.imageData.moveY,
        left: this.imageData.left + this.imageData.moveX
    });
    this.imageData.moveX += moveX;
};
imagePreview.prototype.renderImage = function (base64) {
    var tw = this.Tool.width();
    var th = this.Tool.height();
    var img = $('<img src="' + base64 + '" />');
    this.imageBox.removeClass('TA_f');
    img.css({
        position: 'absolute',
        bottom: '1000%',
    });
    img.on('load', () => {
        this.imageData.width = img.width();
        this.imageData.height = img.height();
        this.imageBox.html('<img src="' + base64 + '" />');
        this.imageElement = this.imageBox;
        this.imageBox.append('<div class="mark"></div>');
        img.remove();
        this.BigControl(tw < this.imageData.width || th < this.imageData.height);
        setTimeout(() => {
            this.imageBox.addClass('TA_f');
        }, 100);
    });
    this.Tool.append(img);
    this.move();
    this.zoomEvent();
};
imagePreview.prototype.clearImage = function () {
    this.imageBox.empty();
};
imagePreview.prototype.setImage = function (index) {
    if (this.data[index].id) {
        this.setImageByUrl(index);
    } else {
        this.setImageByBase64(index);
    }
};
imagePreview.prototype.setImageByUrl = function (index) {
    this.Tool.loadingEX();
    this.title.text(this.data[index].title);
    this.getImage(this.data[index].id, (data) => {
        this.Tool.loadingEX();
        this.renderImage(data.base64);
        this.imageData.title = this.data[index].title;
        this.imageData.data = data.base64;
    })
};
imagePreview.prototype.setImageByBase64 = function (index) {
    this.title.text(this.data[index].title);
    this.renderImage(this.data[index].data);
    this.imageData.title = this.data[index].title;
    this.imageData.data = data.base64;
};
imagePreview.prototype.closeEvent = function () {
    document.onkeydown = function () { };
    this.html.remove();
    $('body').css({
        'user-select': 'text'
    });
};
imagePreview.prototype.showMessage = function (text) {
    this.message.css('opacity', '1').text(text);
    if (this.timer) {
        clearTimeout(this.timer);
    };
    this.timer = setTimeout(() => {
        this.message.css('opacity', '0');
    }, 1000);
};
// 图片显示列表
var imageList = function (data, parent) {
    this.data = data;
    this.parent = parent;
    this.event = this.parent.event;
    this.html = $('<div class="imageList"></div>');
    // this.title = $('<div class="imageList_title">图片列表</div>');
    // .append(this.title)
    this.box = $('<div></div>');
    this.html.append(this.box);
    this.set(data);
    this.imagePreview = new imagePreview(this, this.data, this.event);
};
imageList.prototype.render = function () {
    return this.html;
};
imageList.prototype.set = function (data) {
    this.box.empty();
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.box.append(new imgItem(element, this, true, i).render());
    };
};
// 接口列表
var interfaceList = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.event = this.parent.event;
    this.html = $('<div class="imageList list"></div>');
    // this.title = $('<div class="imageList_title">接口</div>');
    this.box = $('<div></div>');
    this.html
        // .append(this.title)
        .append(this.box);
    this.set(data);
};
interfaceList.prototype.render = function () {
    return this.html;
};
interfaceList.prototype.active = function () {

};
interfaceList.prototype.set = function (data) {
    this.box.empty();
    this.event.getInterface(data, (docs) => {
        for (let i = 0; i < docs.length; i++) {
            const element = new interface(docs[i], this, true);
            this.box.append(element.render());
            element.title.click(() => {
                this.event.jumpInterface(element.config.id);
            });
        };
    });
};
// 单个子对象
var subItem = function (data, parent) {
    this.data = data;
    this.parent = parent;
    this.event = this.parent.event;
    this.html = $('<div class="subItem"></div>');
    this.showBox = $('<div class="showBox"></div>');
    this.titleBox = $('<div class="title"></div>');
    this.title = $('<div class="titleText">' + data.title + '</div>');
    this.description = $('<div class="description">' + data.description.replace(/\r/g, '<br>').replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') + '</div>');
    this.editorButton = $('<div class="fa editor fa-edit" title="编辑"></div>');
    this.deleteButton = $('<div class="fa delete fa-trash-o" title="删除"></div>');
    this.titleBox
        .append(this.title)
        .append(this.editorButton)
        .append(this.deleteButton);
    this.html.append(this.showBox);
    this.editorButton.click(() => {
        this.editorShow();
    });
    this.deleteButton.click(() => {
        this.delete();
    });
    this.imageList = new imageList(data.images, this);
    this.interfaceList = new interfaceList(data.interface, this);
    this.showBox
        .append(this.titleBox)
        .append(this.description)
        .append(this.interfaceList.render())
        .append(this.imageList.render())
        .append('<div class="cf"></div>');
};
subItem.prototype.render = function () {
    return this.html;
};
subItem.prototype.editorShow = function () {
    this.showBox.css('display', 'none');
    this.editorBox = new editorBox(this.data, this);
    this.html.append(this.editorBox.render());
};
subItem.prototype.set = function (ans) {
    this.data = ans;
    this.title.text(ans.title);
    this.imageList.set(ans.images);
    this.interfaceList.set(ans.interface);
    this.description.html(ans.description.replace(/\r/g, '<br>').replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;'));
};
subItem.prototype.remove = function () {
    this.html.remove();
};
subItem.prototype.ImageDispose = function (data, cb) {
    this.event.upDateImage(data.creatImg, (creatImageList) => {
        this.event.deleteImage(data.deleteImg, (deleteImageList) => {
            for (let i = 0; i < data.deleteImg.length; i++) {
                const DeleteElement = data.deleteImg[i];
                for (let y = 0; y < this.data.images.length; y++) {
                    const dataItem = this.data.images[y];
                    if (dataItem.id == DeleteElement) {
                        this.data.images.splice(y, 1);
                        break;
                    };
                };
            };
            for (let i = 0; i < creatImageList.length; i++) {
                const _item = creatImageList[i];
                this.data.images.push(_item);
            };
            cb(this.data.images);
        });
    });
};
subItem.prototype.save = function (data) {
    this.ImageDispose(data.imageList, (newImageList) => {
        var _data = {
            id: this.data.id,
            type: this.data.type,
            description: data.description,
            title: data.title,
            images: newImageList,
            interface: data.answerBox,
            time: this.data.time,
            isNew: false,
            parentId: this.data.parentId,
        };
        if (this.data.isNew) {
            this.event.creat(_data, (doc) => {
                console.log(doc);
                if (this.parent instanceof item) {
                    this.parent.set(doc);
                    this.hide();
                } else if (this.parent instanceof subset) {
                    this.set(doc);
                    this.hide();
                };
            });
        } else {
            this.event.updata(this.data.id, _data, (doc) => {
                this.set(_data);
                this.hide();
            });
        };
    });
};
subItem.prototype.hide = function () {
    this.editorBox.html.remove();
    this.editorBox = null;
    this.showBox.css('display', 'block');
    if (this.data.isNew) {
        if (this.parent instanceof item) {
            this.parent.remove();
        } else if (this.parent instanceof subset) {
            this.html.remove();
        };
    };
};
subItem.prototype.delete = function () {
    dialogEX({
        title: '警告',
        body: '<div style="padding:20px;">是否删除?</div>',
        buttons: [{
            text: '是',
            event: (dialogEvent) => {
                this.html.loadingEX();
                this.event.delete(this.data.id, () => {
                    if (this.parent instanceof item) {
                        this.parent.remove();
                    } else if (this.parent instanceof subset) {
                        this.html.remove();
                    };
                    dialogEvent.close();
                });
            },
        }, {
            text: '否',
            event: (dialogEvent) => {
                dialogEvent.close();
            },
        }],
        width: 400,
        height: 200
    });
};
// 子集菜单对象
var subset = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.event = this.parent.event;
    this.html = $('<div class="subset"></div>');
    this.subsetTitle = $('<div class="subset_title">需求分析 : </div>');
    this.changeButton = $('<div class="fa fa-angle-up changeButton"></div>');
    this.addButton = $('<div class="addButton"><i class="fa fa-plus-circle"></i>添加</div>');
    this.html.append(this.subsetTitle);
    this.box = $('<div style="position: relative; min-height:50px;"></div>');
    this.html.append(this.box);
    this.addButton.click(() => {
        var item = new subItem({
            time: new Date().getTime(),
            parentId: this.data.id,
            title: '',
            description: '',
            type: 'subset',
            interface: [],
            images: [],
            isNew: true,
        }, this);
        this.box.prepend(item.render());
        item.editorShow();
    });
    this.subsetTitle.append(this.changeButton).append(this.addButton)
    this.changeButton.click(() => {
        if (this.status) {
            this.hide();
        } else {
            this.show();
        }
    });
    this.status = false;
    this.hide();
};
subset.prototype.render = function () {
    return this.html;
};
subset.prototype.show = function () {
    this.status = true;
    this.box.empty();
    this.addButton.css('display', 'block');
    this.changeButton.removeClass('fa-angle-down').addClass('fa-angle-up');
    this.box.css('display', 'block');
    this.box.loadingEX();
    this.event.getSubItems(this.data.id, (doc) => {
        this.box.loadingEX();
        for (let i = 0; i < doc.length; i++) {
            const element = doc[i];
            this.box.append(new subItem(element, this).render());
        };
    });
};
subset.prototype.hide = function () {
    this.status = false;
    this.addButton.css('display', 'none');
    this.changeButton.removeClass('fa-angle-up').addClass('fa-angle-down');
    this.box.css('display', 'none');
};
// 需求主对象
var item = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.event = this.parent.event;
    this.html = $('<div class="noteItem"></div>');
    this.line = $('<div class="line"></div>');
    this.time = $('<div class="time">' + formatDate('YYYY年MM月DD日 HH时mm分ss秒', data.time) + '</div>');
    this.point = $('<div class="point"></div>');
    this.content = $('<div class="content"></div>');
    this.mainItem = new subItem(this.data, this);
    this.content.append(this.mainItem.render());
    this.subset = null;
    if (!data.isNew) {
        this.subset = new subset(this.data, this);
        this.content.append(this.subset.render());
    };
    this.html.append(this.line).append(this.time).append(this.point).append('<div style="height:1px;"></div>').append(this.content);
};
item.prototype.render = function () {
    return this.html;
};
item.prototype.remove = function () {
    this.html.remove();
    if (this.parent.item.hasOwnProperty(this.data.id)) {
        delete this.parent.item[this.data.id];
    };
};
item.prototype.set = function (data) {
    this.data = data;
    if (!this.subset) {
        this.subset = new subset(this.data, this);
        this.content.append(this.subset.render());
    };
    this.mainItem.set(data);
};
var scrollObj = function (data, parent) {
    data = data.reverse();
    this.html = $('<div class="scroll custom-scroll theme-scroll"></div>');
    var _dateArray = [];
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        const year = formatDate('YYYY', element.time);
        const mouth = formatDate('MM', element.time);
        const _length = _dateArray.length - 1;
        if (_length < 0 || _dateArray[_length].year != year) {
            _dateArray.push({
                year: year,
                mouth: [{
                    mouth: mouth,
                    id: element.id,
                    title: element.title
                }]
            });
        } else {
            var __length = _dateArray[_length].mouth.length - 1;
            if (_dateArray[_length].mouth[__length].mouth != mouth) {
                _dateArray[_length].mouth.push({
                    mouth: mouth,
                    id: element.id,
                    title: element.title
                });
            }
        };
    };
    for (let i = 0; i < _dateArray.length; i++) {
        const year = _dateArray[i];
        var yearHtml = $('<div class="year"></div>');
        var yearEle = $('<div class="year_num">' + year.year + '年</div>');
        var mouthList = $('<div class="mouthList"></div>');
        for (let y = 0; y < year.mouth.length; y++) {
            const element = year.mouth[y];
            var mouth = $('<div class="mouth_num">' + element.mouth + '月</div>');
            mouth.click(() => {
                parent.active(element.id);
            });
            mouthList.append(mouth);
        };
        yearHtml.append(yearEle).append(mouthList);
        this.html.append(yearHtml);
    };
};
scrollObj.prototype.render = function () {
    return this.html;
};
// 主对象
var note = function () {
    this.html = $('<div id="note" style="display:none"></div>');
    this.box = $('<div class="box"></div>');
    this.scroll = null;
    // this.scroll = $('<div class="scroll custom-scroll theme-scroll"></div>');
    this.html.append(this.box);
    // .append(this.scroll);
    this.event = {
        refresh: function () { },
        getSubItems: function () { },
        getImages: function () { },
        getInterface: function () { },
        jumpInterface: function () { },
        creat: function () { },
        delete: function () { },
        updata: function () { },
        creatNew: this.creatNew,
        upDateImage: function () { },
        deleteImage: function () { },
        searchInterface: function () { },
    };
    this.addButton = null;
    this.item = {};
    this.data = [];
};
note.prototype.show = function () {
    this.html.css({ display: 'block' });
};
note.prototype.hide = function () {
    this.html.css({ display: 'none' });
};
note.prototype.render = function () {
    return this.html;
};
note.prototype.refresh = function () {
    this.html.loadingEX();
    this.clear();
    this.event.refresh(this, (data) => {
        this.data = data;
        this.renderList(data);
        this.scroll = new scrollObj(data, this);
        this.html.append(this.scroll.render());
        this.renderAddButton();
        this.html.loadingEX();
    });
};
note.prototype.jumpInterface = function (data) {
    this.event.jumpInterface(data);
};
note.prototype.on = function (str, event) {
    if (this.event.hasOwnProperty(str)) {
        this.event[str] = event;
    };
};
note.prototype.renderAddButton = function () {
    this.addButton = $('<div class="noteItem">\
                            <div class="line"></div>\
                            <div class="time">现在</div>\
                            <div class="point"></div>\
                            <div style="height:1px;"></div>\
                            <div class="content add" style="width: 74px; font-size:14px; color:#666;">\
                                <i class="fa fa-plus-circle" style="color: #3399ff;margin:0 5px 0 0"></i>点击添加\
                            </div>\
                            <div class="content refresh" style="width: 74px; font-size:14px; color:#666;">\
                            <i class="fa fa-refresh" style="color: #3399ff;margin:0 5px 0 0"></i>刷新\
                        </div>\
                        </div>');
    this.box.prepend(this.addButton);
    this.addButton.find('.add').click(() => {
        var _item = new item({
            time: new Date().getTime(),
            title: '',
            description: '',
            type: 'main',
            interface: [],
            images: [],
            isNew: true,
            parentId: null,
        }, this);
        this.addButton.after(_item.render());
        _item.mainItem.editorShow();
    });
    this.addButton.find('.refresh').click(() => {
        this.refresh();
    });
};
note.prototype.renderList = function (docs) {
    for (let i = 0; i < docs.length; i++) {
        this.append(docs[i]);
    };
};
note.prototype.clear = function () {
    this.item = {};
    this.box.empty();
    if (this.scroll) {
        this.scroll.html.remove();
        this.scroll = null;
    };
    this.addButton = null;
};
note.prototype.append = function (data) {
    const element = data;
    var _item = new item(element, this);
    this.item[element.id] = _item;
    if (this.addButton) {
        this.addButton.after(_item.render());
    } else {
        this.box.prepend(_item.render());
    };
};
note.prototype.creatNew = function (EditorObj, data) {
    this.creat(data, (doc) => {
        EditorObj.html.remove();
        this.append(doc);
    });
};
note.prototype.active = function (id) {
    var obj = this.item[id].html;
    var Min = 0;
    var Max = this.html.height();
    var top = obj.offset().top;
    var height = this.item[id].html.height();

    if (height < Max) {
        this.afterMove(obj);
        return;
    };

    if (top < 50) {
        this.html.scrollTop(this.html.scrollTop() - 30);
        this.itemMoveUp(obj);
    } else if (top > 120) {
        this.html.scrollTop(this.html.scrollTop() + 30);
        this.itemMoveDown(obj);
    } else {
        this.afterMove(obj);
    };
};
note.prototype.itemMoveUp = function (obj) {
    var moveObj = () => {
        var top = obj.offset().top;
        if (top < 50) {
            this.html.scrollTop(this.html.scrollTop() - 30);
            setTimeout(() => {
                moveObj();
            }, 5)
        } else {
            this.afterMove(obj);
        };
    };
    moveObj();
};
note.prototype.itemMoveDown = function (obj) {
    var moveObj = () => {
        var top = obj.offset().top;
        if (top > 120) {
            this.html.scrollTop(this.html.scrollTop() + 30);
            setTimeout(() => {
                moveObj();
            }, 5)
        } else {
            this.afterMove(obj);
        };
    };
    moveObj();
};
note.prototype.afterMove = function (obj) {
    obj.addClass('interface_flicker');
    setTimeout(() => {
        obj.removeClass('interface_flicker');
    }, 500);
}


module.exports = function () {
    return new note();
};